package utils

import (
	"excel/types"
	"fmt"
	"regexp"
	"strconv"
	"strings"
	"time"

	"github.com/xuri/excelize/v2"
)

func ReadExcel(path, sheet string, res *[]types.ExcelDemo) error {
	f, err := excelize.OpenFile(path)
	if err != nil {
		return err
	}
	defer func() {
		if err := f.Close(); err != nil {
			fmt.Println(err)
		}
	}()

	// 查找需要的sheet
	for _, name := range f.GetSheetMap() {
		if strings.Contains(name, sheet) {
			rows, err := f.GetRows(name)
			if err != nil {
				return err
			}
			fields := make(map[string]int)
			for index, row := range rows {
				// 跳过表头
				if index == 0 {
					for id, colCell := range row {
						fields[colCell] = id
					}
				} else {
					for range fields {
						if len(fields) > len(row) {
							row = append(row, "")
						}
					}
					origin1 := row[fields["籍贯省"]]
					origin2 := row[fields["籍贯市"]]
					origin3 := row[fields["籍贯区"]]
					if origin3 == "" {
						origin3 = "新昌县"
					}
					if origin2 == "" {
						origin2 = "绍兴市"
					}
					if origin1 == "" {
						origin1 = "浙江省"
					}
					status := row[fields["编制状态"]]
					var personal string
					bType := row[fields["编制类型"]]
					if status != "在编" {
						status = "非编"
						personal = "教师"
						bType = ""
					} else {
						personal = ""
						if bType == "" {
							bType = "事业单位人员编制"
						}
					}
					idno := row[fields["证件号码"]]
					birthDay := ""
					if len(idno) == 18 {
						date, _ := time.Parse("20060102", idno[6:14])
						birthDay = date.Format("2006-01-02")
					}
					updatedAt := row[fields["入编时间"]]
					// if updatedAt == "" {
					// 	updatedAt = "2024-04-24"
					// }

					cell := types.ExcelDemo{
						Name:      row[fields["姓名"]],
						Sex:       row[fields["性别"]],
						Nation:    row[fields["民族"]],
						IDType:    row[fields["证件类型"]],
						IDNo:      idno,
						Mobile:    row[fields["手机号"]],
						Birth1:    row[fields["出生地省"]],
						Birth2:    row[fields["出生地市"]],
						Birth3:    row[fields["出生地区"]],
						Origin1:   origin1,
						Origin2:   origin2,
						Origin3:   origin3,
						BirthDay:  birthDay,
						Address:   row[fields["详细地址"]],
						Work:      row[fields["工作单位"]],
						Under:     row[fields["隶属集团"]],
						Status:    status,
						Unit:      row[fields["编制单位(工作单位)"]],
						Type:      bType,
						UpdatedAt: FormatDate(updatedAt),
						Personal:  personal,
						CreatedAt: FormatDate(row[fields["入单位时间"]]),
						Job:       row[fields["岗位分类"]],
					}

					*res = append(*res, cell)
				}
			}
		}
	}
	return nil
}

func FormatDate(timeStr string) string {
	if len(timeStr) < 5 {
		return ""
	}
	timeStr = strings.ReplaceAll(timeStr, "/", "-")
	timeStr = strings.ReplaceAll(timeStr, ".", "-")
	timeStr = strings.ReplaceAll(timeStr, "年", "-")
	timeStr = strings.ReplaceAll(timeStr, "月", "-")
	timeStr = strings.ReplaceAll(timeStr, "零", "0")
	timeStr = strings.ReplaceAll(timeStr, " ", "")
	if timeStr[len(timeStr)-1:] == "-" {
		timeStr = timeStr + "01"
	}
	pattern0 := regexp.MustCompile(`-`)
	if matches := pattern0.FindAllString(timeStr, -1); len(matches) == 1 {
		timeStr = timeStr + "-01"
	}
	if matches := pattern0.FindAllString(timeStr, -1); len(matches) == 2 && len(timeStr) == 8 {
		days, _ := time.Parse("01-02-06", timeStr)
		timeStr = days.Format("2006-01-02")
	}
	if len(timeStr) == 5 {
		days, _ := strconv.Atoi(timeStr)
		baseDate := time.Date(1900, time.January, 1, 0, 0, 0, 0, time.UTC)
		excelDate := baseDate.AddDate(0, 0, days)
		timeStr = excelDate.Format("2006-01-02")
	}
	if len(timeStr) == 6 {
		return timeStr[:4] + "-" + timeStr[4:] + "-01"
	}
	if len(timeStr) != 10 {
		arr := strings.Split(timeStr, "-")
		if len(arr) == 3 {
			if len(arr[1]) == 1 {
				arr[1] = "0" + arr[1]
			}
			if len(arr[2]) == 1 {
				arr[2] = "0" + arr[2]
			}
		}
		timeStr = strings.Join(arr, "-")
	}
	return timeStr
}
